package com.chant.startFarming.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chant.startFarming.entity.Menus;
import com.chant.startFarming.mapper.MenusMapper;
import com.chant.startFarming.service.IMenusService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统菜单表 服务实现类
 * </p>
 *
 * @author chant
 * @since 2025-04-06
 */
@Service
public class MenusServiceImpl extends ServiceImpl<MenusMapper, Menus> implements IMenusService {

    @Override
    public List<Menus> getMenusByRole(Integer role) {
        QueryWrapper<Menus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_status", 1); // 只返回启用的菜单
        queryWrapper.orderByAsc("sort"); // 按排序字段排序

        if (role == 2) {
            queryWrapper.eq("required_role", 2); // 普通用户只能访问 required_role=2 的菜单
        }

        List<Menus> menus = list(queryWrapper);
        return buildTree(menus);
    }

    /**
     * 构建树形结构菜单
     */
    private List<Menus> buildTree(List<Menus> menus) {
        List<Menus> tree = new ArrayList<>();
        if (menus == null || menus.isEmpty()) {
            return tree;
        }

        // 将菜单数据存入 Map，方便查找
        Map<Integer, Menus> menuMap = new HashMap<>();
        menus.forEach(menu -> menuMap.put(menu.getId(), menu));

        // 构建树形结构
        for (Menus menu : menus) {
            if (menu.getParentId() == 0) {
                tree.add(menu);
            } else {
                Menus parent = menuMap.get(menu.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(menu);
                }
            }
        }

        return tree;
    }
}
